package com.dzsw.netty.future;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;

public class EventLoop implements Runnable {

    public static final int STATUS_ON = 1;

    public static final int STATUS_OFF = 0;

    private volatile int status = STATUS_ON;

    private Thread t;

    private BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue();

    public EventLoop() {
        t = new Thread(this);
        t.setName("Eventloop Thread ");
        t.start();
    }

    public void stop() {
        status = STATUS_OFF;
            t.interrupt();
    }

    public Future submit(Callable callable) throws Exception {
        FutureTask task = new FutureTask(callable);
        taskQueue.put(task);
        return task;
    }

    public void submit(Runnable runnable) throws Exception {
        taskQueue.put(runnable);
    }

    @Override
    public void run() {
        for(;status == STATUS_ON;) {
            try {
                Runnable task = taskQueue.take();
                task.run();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
